package cn.stylefeng.guns.modular.business.frequency.statistics;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.modular.business.custom.constant.PublicCommon;
import cn.stylefeng.guns.modular.business.custom.enums.OrderStatusEnum;
import cn.stylefeng.guns.modular.business.frequency.appmessage.mapper.AppMessageMapper;
import cn.stylefeng.guns.modular.business.frequency.appmessage.model.param.AppMessageParam;
import cn.stylefeng.guns.modular.business.frequency.finance.model.result.PkgFinance;
import cn.stylefeng.guns.modular.business.frequency.orderfinish.mapper.OrderFinishMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.mapper.OrderPickMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.result.PkgOrderPick;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordertake.mapper.OrderTakeMapper;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.mapper.TransportMapper;
import cn.stylefeng.guns.modular.business.frequency.transportsign.mapper.TransportSignMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.sys.modular.user.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author jzy
 * @Date 2020/11/23 0023
 **/
@Service
public class StatisticsService  {

    @Resource
    private OrderSubMapper statisticsMapper;
    @Resource
    private SysSiteMapper siteMapper;
    @Resource
    private OrderPickMapper pickCarMapper;
    @Resource
    private TransportMapper transportMapper;
    @Resource
    private TransportSignMapper orderSignMapper;
    @Resource
    private OrderTakeMapper orderTakeMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private OrderFinishMapper orderFinishMapper;

    @Resource
    private AppMessageMapper appMessageMapper;

    @Resource
    private BusinessUtil businessUtil;

    public PkgDailyDataStatistics getDailyData(String month) {
        return statisticsMapper.getDailyData(month);
    }

    public List<PkgMonthDataStatistics> getMonthGrossData(String month) {
        return statisticsMapper.getMonthGrossData(month);
    }

    public PkgFinance getMonthCollectionPaymentData(String month) {
        return statisticsMapper.getMonthCollectionPaymentData(month);
    }

    public List<PkgMonthDataStatistics> getMonthBusinessData(String month) {
        return statisticsMapper.getMonthBusinessData(month);
    }


    /**  月度网点业务量统计  */
    public HashMap<String, Object> getMonthSiteBusinessData(String month) {
        List<PkgMonthDataStatistics> list = statisticsMapper.getMonthSiteOrderCount(month);
        HashMap<String, Object> map = new HashMap<>();

//        map.put("siteName", list.stream().map(s -> s.getSiteName()).collect(Collectors.toList()));
//        map.put("orderCount", list.stream().map(s -> s.getOrderCount()).collect(Collectors.toList()));
        List<Integer> pickCount = statisticsMapper.getMonthSitePickCount(month);
//        map.put("pickCount", pickCount);
        List<Integer> transportCount = statisticsMapper.getMonthSiteTransportCount(month);
//        map.put("transportCount", transportCount);
        List<Integer> deliveryCount = statisticsMapper.getMonthSiteDeliveryCount(month);
        List<Integer> signCount = statisticsMapper.getMonthSiteSignCount(month);
//        map.put("deliveryCount", deliveryCount);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPickCount(pickCount.get(i));
            list.get(i).setTransportCount(transportCount.get(i));
            list.get(i).setDeliveryCount(deliveryCount.get(i));
            list.get(i).setSignCount(signCount.get(i));
            list.get(i).setTotalCount(list.get(i)
                    .getOrderCount() + pickCount.get(i) + transportCount.get(i) + deliveryCount.get(i) + signCount.get(i));
        }
        List<PkgMonthDataStatistics> sortedList;
        sortedList = list.stream().sorted(Comparator.comparing(PkgMonthDataStatistics::getTotalCount))
                .collect(Collectors.toList());
        map.put("siteName", sortedList.stream().map(PkgMonthDataStatistics::getSiteName).collect(Collectors.toList()));
        map.put("orderCount", sortedList.stream().map(PkgMonthDataStatistics::getOrderCount)
                .collect(Collectors.toList()));
        map.put("pickCount", sortedList.stream().map(PkgMonthDataStatistics::getPickCount)
                .collect(Collectors.toList()));
        map.put("transportCount", sortedList.stream().map(PkgMonthDataStatistics::getTransportCount)
                .collect(Collectors.toList()));
        map.put("signCount", sortedList.stream().map(PkgMonthDataStatistics::getSignCount)
                .collect(Collectors.toList()));
        map.put("deliveryCount", sortedList.stream().map(PkgMonthDataStatistics::getDeliveryCount)
                .collect(Collectors.toList()));
        return map;
    }

    public IndexDataVO getIndexData() {
        IndexDataVO data = new IndexDataVO();
        // 当前时间
        data.setCurrentDate(System.currentTimeMillis());
        OrderDTO orderDTO = new OrderDTO();
        List<Long> orgList = businessUtil.getEmpByOrgList();
        Long siteId = businessUtil.getSiteId();
        Long tenantId = businessUtil.getTenantId();
        orderDTO.setDataList(orgList);

        // 当日订单
        // 当月订单
        // 上月订单
        IndexDataVO dataVO = statisticsMapper.getOrderAllCount(tenantId);
        BeanUtils.copyProperties(dataVO,data);



        // -------------以下各项与时间无关
        // 提车数量
        PickDTO pickDTO = new PickDTO();
        pickDTO.setStatusOnly(OrderStatusEnum.NEW_ORDER.status);
        pickDTO.setDataList(orgList);
        data.setPickCount(pickCarMapper.getWaiDealOrderNum(pickDTO, tenantId));
        //最新提车消息的时间

        // 验车数量
        PickDTO verifyDTO = new PickDTO();
        verifyDTO.setStatusOnly(OrderStatusEnum.WAIT_PICK.status);
        verifyDTO.setDataList(orgList);
        data.setVerifyCount(pickCarMapper.getWaiVerifyOrderNum( verifyDTO, tenantId));

        // 发运数量
        OrderDTO transportDTO = new OrderDTO();
        transportDTO.setDataList(orgList);
        transportDTO.setTenantId(tenantId);
        data.setTransportCount(transportMapper.getWaitTransportOrderNum(transportDTO));
        // 在途数量
        OrderDTO logisticsDTO = new OrderDTO();
        logisticsDTO.setDataList(orgList);
        data.setLogisticsCount(statisticsMapper.countLogistics(logisticsDTO, tenantId));
        // 签收数量
        OrderDTO signDTO = new OrderDTO();
        signDTO.setDataList(orgList);
        signDTO.setTenantId(tenantId);
        data.setSignCount(orderSignMapper.getWaitSignOrderListNum( signDTO));
        // 签收数量
        AppMessageParam appMessageParam = new AppMessageParam();
        appMessageParam.setMessageType(4);
        appMessageParam.setTenantId(tenantId);
        //获取当前登录人权限

        if(orgList!=null&&orgList.size()==0){
            orgList.add(-1l);
        }
        appMessageParam.setDataList(orgList);
        if(siteId!=null){
            appMessageParam.setSiteId(siteId);
        }else {
            appMessageParam.setSiteId(-1l);
        }
        data.setArriveSignCount(appMessageMapper.getPageNum( appMessageParam));
        // 中转待签 签收数量
        appMessageParam.setMessageType(3);
        data.setTransitSignCount(appMessageMapper.getPageNum( appMessageParam));

        // 送车数量
        OrderDTO takeDTO = new OrderDTO();
        takeDTO.setStatusOnly(OrderStatusEnum.FINISHED_TRANSPORT.status);
        if(siteId==null){
            takeDTO.setDataList(orgList);
        }else {
            takeDTO.setSiteId(siteId);
            takeDTO.setUserId(LoginContextHolder.me().getSysLoginUserId().toString());
        }
        takeDTO.setTenantId(tenantId);
        data.setTakeCount(orderTakeMapper.getWaitTakeNum(takeDTO));
        // 交付数量
        OrderDTO finishDTO = new OrderDTO();

        if(siteId==null){
            finishDTO.setDataList(orgList);
        }else {
            finishDTO.setSiteId(siteId);
        }
        finishDTO.setTenantId(tenantId);
        data.setFinishCount(orderFinishMapper.getWaitFinishListNum( finishDTO));
        //最新提车消息的时间


        return data;
    }

    private void getLogisticsQueryParam(OrderDTO logisticsDTO) {
        //String maxDataScope = SecurityUtil.getCurrentUserMaxDataScope();
        //if (!maxDataScope.equals(DataScopeEnum.ALL.getValue())) {
        //    logisticsDTO.setUserId(SecurityUtil.getCurrentUserId(1));
        //}
        List<Long> orgList = businessUtil.getEmpByOrgList();
        logisticsDTO.setDataList(orgList);
    }

    private void getFinishWaitQueryParam(OrderDTO orderDTO) {
        //JwtUserDTO user = (JwtUserDTO) SecurityUtil.getCurrentUser(1);
        //String maxDataScope = SecurityUtil.getCurrentUserMaxDataScope();
        //if (!maxDataScope.equals(DataScopeEnum.ALL.getValue())) {
        //    if (user.getUser().getDept().getHasSite() == 1 && StringUtils.isNotBlank(user.getUser().getDept().getSiteId())) {
        //        // 网点用户
        //        orderDTO.setUserId(user.getUser().getId());
        //        orderDTO.setSiteId(user.getUser().getDept().getSiteId());
        //    } else {
        //        // 非网点用户
        //        if (maxDataScope.equals(DataScopeEnum.THIS_LEVEL.getValue())) {
        //            // 本部门
        //            orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //        } else if (maxDataScope.equals(DataScopeEnum.SELF.getValue())) {
        //            // 自己
        //            orderDTO.setUserId(user.getUser().getId());
        //        } else if (maxDataScope.equals(DataScopeEnum.CUSTOMIZE.getValue())) {
        //            // 自定义部门
        //            List<String> deptIds = userMapper.getRoleDeptIdsByUserId(user.getUser().getId());
        //            orderDTO.setDeptIds(deptIds);
        //        }
        //    }
        //}

        if(businessUtil.getSiteId()==null){
            List<Long> orgList = businessUtil.getEmpByOrgList();
            orderDTO.setDataList(orgList);
        }else {
            orderDTO.setSiteId(businessUtil.getSiteId());
        }





    }

    private void getOrderTakeQueryParam(OrderDTO orderDTO) {
        // 1. 管理员和总调度可以看到全部数据
        // 2. 普通调度只能看到到货该网点的数据以及自己发运的
        // 3. 业务只能看到自己发运的数据
        //JwtUserDTO user = (JwtUserDTO) SecurityUtil.getCurrentUser(1);
        //// 最高数据权限
        //List<String> dataScopeList = user.getUser().getRoles().stream().map(RoleSmallDTO::getDataScope).collect(Collectors.toList());
        //if (!SecurityUtil.isAdmin()) {
        //    // 1.1 用户部门是不是网点
        //    if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 1) {
        //        // 1.1.1 是网点
        //        if (!dataScopeList.contains(DataScopeEnum.ALL)) {
        //            if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 1
        //                    && StringUtils.isNotBlank(user.getUser().getDept().getSiteId())) {
        //                // 网点 siteId
        //                orderDTO.setSiteId(user.getUser().getDept().getSiteId());
        //                orderDTO.setUserId(user.getUser().getId());
        //            }
        //        }
        //    } else if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 0) {
        //        // 1.1.2 不是网点 ==> 业务人员
        //        if (SecurityUtil.getDataScopeType() == 2) {
        //            // 1.1.2.1 业务主管
        //            orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //        } else if (SecurityUtil.getDataScopeType() == 3) {
        //            // 1.1.2.2 业务人员
        //            orderDTO.setUserId(user.getUser().getId());
        //        }
        //    }
        //}
        if(businessUtil.getSiteId()==null){
            List<Long> orgList = businessUtil.getEmpByOrgList();
            orderDTO.setDataList(orgList);
        }else {
            orderDTO.setSiteId(businessUtil.getSiteId());
            orderDTO.setUserId(LoginContextHolder.me().getSysLoginUserId().toString());
        }
    }

    private void getSignQueryParam(OrderDTO orderDTO) {


        List<Long> orgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(orgList);
    }

    private void getWaitTransportQueryParam(OrderDTO orderDTO) {
        // 数据权限
        // 1. 管理员和总调度可以看到全部数据
        // 2. 普通调度只能看到负责城市的数据
        //JwtUserDTO user = (JwtUserDTO) SecurityUtil.getCurrentUser(1);
        //String maxDataScope = SecurityUtil.getCurrentUserMaxDataScope();
        //// 最高数据权限
        //List<String> dataScopeList = user.getUser().getRoles().stream().map(RoleSmallDTO::getDataScope).collect(Collectors.toList());
        //// ----------2020-20-21-----修改
        //if (!maxDataScope.equals(DataScopeEnum.ALL.getValue())) {
        //    //orderDTO.setUserId(SecurityUtil.getCurrentUserId());
        //    // 1.1 用户部门是不是网点
        //    if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 1) {
        //        // 1.1.1 是网点
        //        orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //        orderDTO.setDispatcherId(user.getUser().getId());
        //        if (!dataScopeList.contains(DataScopeEnum.CUSTOMIZE.getValue())) {
        //            List<String> chargeCityList = siteMapper.getServiceCodes(user.getUser().getDept().getSiteId());
        //            orderDTO.setStartCodeList(chargeCityList);
        //        } else {
        //            // 自定义部门权限
        //            List<String> siteIds = deptMapper.getDeptByUserId(user.getUser().getId());
        //            List<String> chargeCityList = siteMapper.getServiceCodesBySiteIds(siteIds);
        //            orderDTO.setStartCodeList(chargeCityList);
        //            List<String> deptIds = userMapper.getRoleDeptIdsByUserId(user.getUser().getId());
        //            orderDTO.setDeptIds(deptIds);
        //        }
        //    } else if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 0) {
        //        // 1.1.2 不是网点 ==> 业务人员
        //        if (maxDataScope.equals(DataScopeEnum.THIS_LEVEL.getValue())) {
        //            // 1.1.2.1 业务主管
        //            orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //        } else if (maxDataScope.equals(DataScopeEnum.SELF.getValue())) {
        //            // 1.1.2.2 业务人员
        //            orderDTO.setUserId(user.getUser().getId());
        //        }
        //    }
        //}

        List<Long> orgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(orgList);
    }

    private void getPickQueryParam(OrderDTO orderDTO) {
        // 数据权限
        // 1. 管理员可以看到全部数据
        // 2. 普通调度只能看到负责城市的数据
        //JwtUserDTO user = (JwtUserDTO) SecurityUtil.getCurrentUser(1);
        //// 最高数据权限
        //List<String> dataScopeList = user.getUser().getRoles().stream().map(RoleSmallDTO::getDataScope).collect(Collectors.toList());
        //
        //// ----------2020-10-21-----修改
        //if (!SecurityUtil.isAdmin()) {
        //    // 1.1 用户部门是不是网点
        //    if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 1) {
        //        // 1.1.1 是网点
        //        if (!dataScopeList.contains(DataScopeEnum.ALL.getValue())) {
        //            orderDTO.setDispatcherId(user.getUser().getId());
        //            if (!dataScopeList.contains(DataScopeEnum.CUSTOMIZE.getValue())) {
        //                List<String> chargeCityList = siteMapper.getServiceCodes(user.getUser().getDept().getSiteId());
        //                orderDTO.setStartCodeList(chargeCityList);
        //            } else {
        //                // 自定义部门权限
        //                List<String> siteIds = deptMapper.getDeptByUserId(user.getUser().getId());
        //                List<String> chargeCityList = siteMapper.getServiceCodesBySiteIds(siteIds);
        //                orderDTO.setStartCodeList(chargeCityList);
        //            }
        //        }
        //    } else if (user.getUser().getDept() != null && user.getUser().getDept().getHasSite() == 0) {
        //        // 1.1.2 不是网点 ==> 业务人员
        //        if (SecurityUtil.getDataScopeType() == 2) {
        //            // 1.1.2.1 业务主管
        //            orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //        } else if (SecurityUtil.getDataScopeType() == 3) {
        //            // 1.1.2.2 业务人员
        //            orderDTO.setUserId(user.getUser().getId());
        //        }
        //    }
        //}
        //

        List<Long> orgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(orgList);

    }


    /** 客户下单月度排名 */
    public Map<String, Object> getLinkmanOrderRank(String month) {
        List<PkgMonthDataStatistics> list = statisticsMapper.getLinkmanOrderRank(month);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        map.put("total", list.stream().mapToInt(PkgMonthDataStatistics::getOrderCount).sum());
        return map;
    }

    /** 客户承运月度排名 */
    public Map<String, Object> getLinkmanTransportRank(String month) {
        List<PkgMonthDataStatistics> list = statisticsMapper.getLinkmanTransportRank(month);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        map.put("total", list.stream().mapToInt(PkgMonthDataStatistics::getOrderCount).sum());
        return map;
    }
}
